package com.hmall.item.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmall.common.client.OrderClient;
import com.hmall.common.dto.Order;
import com.hmall.common.dto.OrderDetail;
import com.hmall.item.mapper.OrderDetailMapper;
import com.hmall.item.mapper.OrderMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.ItemService;
import com.hmall.item.web.ItemController;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 监听失效订单
 */
@Component
public class OrderListener {

    @Autowired(required = false)
    OrderMapper orderMapper;
    @Autowired(required = false)
    OrderDetailMapper orderDetailMapper;
    @Autowired(required = false)
    OrderClient orderClient;
    @Autowired(required = false)
    ItemService itemService;
    @Autowired(required = false)
    ItemController itemController;


    @RabbitListener(queues = "dl.queue")
    public void handleOrderMsg(Long id){

        //查询过期订单
        Order order = orderMapper.selectById(id);

        //如果订单未超时支付
        if (order.getStatus()==5){
            //查询订单详情,获取商品信息
            QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id",id);
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper);
            //遍历订单中所有商品
            orderDetailList.forEach(orderDetail -> {
                Long itemId = orderDetail.getItemId();
                Integer num = orderDetail.getNum();
                Item item = itemService.findById(itemId);
                //修改商品库存和销量信息
                item.setSold(item.getSold()-num);
                item.setStock(item.getStock()+num);
                //调用商品更新方法更新商品
                itemController.update(item);
            });
        }

    }
}